package com.dudu.access;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.dudu.bean.DialResultBean;
import com.dudu.bean.IMSBilBean;
import com.dudu.bean.ImsChargeBean;
import com.dudu.bean.PoolAbilityInfoBean;
import com.dudu.bean.ResultQueryBillBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.Encrypt;
import com.dudu.utils.HttpRequest;
import com.dudu.utils.ProperyResource;

/**
 * IMS 点击拨号（双方通话）Util
 * 
 * @author
 * 
 */
public class IMSDialUtils {

    private static final Logger log = core.util.Logger.getLogger(IMSDialUtils.class.getName());
    private static ILogService logService = new LogService();

    public static void main(String[] args) {

	Map<String, String> mMaps = new HashMap<String, String>();

	mMaps.put("15359102144", "09722696");
	mMaps.put("15359114901", "93584836");
	mMaps.put("15359127834", "07643728");
	mMaps.put("15359138584", "08350319");
	mMaps.put("15359152549", "00937508");
	mMaps.put("15359164980", "03958236");
	mMaps.put("15359184742", "02037485");
	mMaps.put("15359195437", "27391712");
	mMaps.put("15359740475", "59326148");
	mMaps.put("15375911545", "43178682");
	mMaps.put("15377929462", "92015703");
	mMaps.put("15394410419", "31313133");
	mMaps.put("15394534619", "44247808");
	mMaps.put("18050141804", "75171625");
	mMaps.put("18050224091", "60992446");
	mMaps.put("18050345534", "57489009");
	mMaps.put("18050766664", "85734390");
	mMaps.put("18059022074", "11090904");
	mMaps.put("18059064065", "61700297");
	mMaps.put("18059124226", "35273554");
	mMaps.put("18059165864", "87541200");
	mMaps.put("18059767449", "33337207");
	mMaps.put("18060570245", "76845605");
	mMaps.put("18060584361", "58212929");
	mMaps.put("18060603461", "53710730");
	mMaps.put("18060672641", "22299561");
	mMaps.put("18060676043", "60375482");
	mMaps.put("18060683824", "85967138");
	mMaps.put("18060731942", "09251879");
	mMaps.put("18060759423", "18125505");
	mMaps.put("13328307594", "71164082");
	mMaps.put("13328790427", "24226547");
	mMaps.put("13365043186", "17187870");
	mMaps.put("13394060187", "62189928");
	mMaps.put("15305047451", "79350485");
	mMaps.put("15359246763", "93573681");
	mMaps.put("15359356409", "17012355");
	mMaps.put("15359862042", "88323508");
	mMaps.put("15394462731", "05116982");
	mMaps.put("15396223524", "57426250");
	mMaps.put("18046240501", "08114827");
	mMaps.put("18046245742", "48006999");
	mMaps.put("18046274227", "25860181");
	mMaps.put("18144080827", "53363460");
	mMaps.put("18144141081", "88069191");
	mMaps.put("13313724452", "51614701");
	mMaps.put("13338201594", "94282221");
	mMaps.put("13338221734", "68289012");
	mMaps.put("13348411714", "60856633");
	mMaps.put("13348414732", "70780520");
	mMaps.put("13348419649", "44730601");
	mMaps.put("13376937605", "80587374");
	mMaps.put("15359704707", "23291869");
	mMaps.put("13328845894", "30973780");
	mMaps.put("15396153844", "69068312");
	mMaps.put("18950796564", "93221775");
	mMaps.put("18150476430", "33493528");
	mMaps.put("13306944621", "04363828");
	mMaps.put("13348473147", "56261378");
	mMaps.put("13328499504", "13971091");
	mMaps.put("13313804232", "46615792");
	mMaps.put("13328614546", "06539230");
	mMaps.put("18094147985", "05367031");

	for (Map.Entry<String, String> entry : mMaps.entrySet()) {

	    // System.out.println("Key = " + entry.getKey() + ", Value = "
	    // +entry.getValue());

	    // postACCOUNT(entry.getKey(), entry.getValue());

	    /*
	     * NumberPool nuberPool = new NumberPool();
	     * nuberPool.setImsAccount(entry.getKey()); nuberPool.setImsKey(
	     * entry.getValue());
	     * 
	     * ImsUtils.talksV2("18911850097", "17001090102", nuberPool);
	     * 
	     * try { Thread.sleep(10000); } catch (InterruptedException e) {
	     * e.printStackTrace(); }
	     */

	}

    }

    /**
     * 选号
     * 
     * @return
     */
    public static String IMS_QUERY() {
	// JSONObject object = new JSONObject();
	// 请求参数
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
	String timestamp = sdf.format(Calendar.getInstance().getTime());
	StringBuffer urlBuffer = new StringBuffer(ProperyResource.getServiceUrl());
	urlBuffer.append("?postData=<Request><Head><MethodName>IMS_QUERY</MethodName>");
	urlBuffer.append("<Spid>").append(ProperyResource.getSpId()).append("</Spid>");
	urlBuffer.append("<Appid>").append("223").append("</Appid>");
	urlBuffer.append("<Passwd>").append(Encrypt.sha1Encrypt(ProperyResource.getPassword())).append("</Passwd>");
	urlBuffer.append("<Timestamp>").append(timestamp).append("</Timestamp>");
	urlBuffer.append("<Authenticator>").append(Encrypt.sha1Encrypt(timestamp + "IMS_QUERY" + ProperyResource.getSpId() + ProperyResource.getPassword()))
		.append("</Authenticator>");
	urlBuffer.append("</Head><Body>");
	urlBuffer.append("<AreaCode></AreaCode><Number></Number>");
	urlBuffer.append("</Body></Request>");

	String data = HttpRequest.getData(urlBuffer.toString());

	return data;
    }

    /**
     * 查询余额
     * 
     * @param chargeNbr
     *            IMS账号
     * @param chargeKey
     *            IMS密码
     * @return
     */
    public static String postACCOUNT(String chargeNbr, String chargeKey) {

	StringBuffer urlBuffer = new StringBuffer();
	urlBuffer.append("<Request><Head><MethodName>IMS_ACCOUNT</MethodName>");
	urlBuffer.append("<Spid>" + ProperyResource.getSpId() + "</Spid>");
	urlBuffer.append("<Appid>" + ProperyResource.getAppId() + "</Appid>");
	urlBuffer.append("<Passwd>" + Encrypt.sha1Encrypt(ProperyResource.getPassword()) + "</Passwd>");
	urlBuffer.append("</Head><Body>");
	urlBuffer.append("<Ims>" + chargeNbr.trim() + "</Ims><Key>" + chargeKey.trim() + "</Key><Type>1</Type></Body></Request>");
	String url=ProperyResource.getServiceUrl()+"?postData="+ URLEncoder.encode(urlBuffer.toString());
	log.debug("查询余额请求---send time account request:" + url);
	// System.out.println("查询余额请求---send time account request:"+urlBuffer);

	String returnData = HttpRequest.getData(url);

	log.debug("查询余额响应---send time account response:" + returnData);

	// System.out.println("查询余额响应---send time account response:"+returnData);

	return returnData;

    }

    /**
     * 解释查询余额报文 <Response> <Head> <Result>0</Result> <ResultDesc>成功</ResultDesc>
     * </Head> <Body> <Ims>8659585943903</Ims> <AllPoint>997273</AllPoint>
     * <PerValue>1.0</PerValue> <EffectDate>2016-03-30 17:38:27.0</EffectDate>
     * <Status>0</Status> </Body> </Response>
     * 
     * @param xml
     * @param chargeNbr
     *            IMS账号
     * @param chargeKey
     *            IMS密码
     * @return
     */
    public static ImsChargeBean parseAccountAndOrder(String xml, String chargeNbr, String chargeKey) {

	ImsChargeBean charge = new ImsChargeBean();

	charge.setCharge_no(chargeNbr);
	charge.setCharge_key(chargeKey);
	charge.setApp_id(ProperyResource.getAppId());

	try {
	    Document doc = DocumentHelper.parseText(xml);
	    Element root = doc.getRootElement();
	    Element head = root.element("Head");
	    Element body = root.element("Body");
	    String result = head.elementTextTrim("Result");
	    String AllPoint = body.elementTextTrim("AllPoint");
	    String EffectDate = body.elementTextTrim("EffectDate");

	    charge.setResult(result);
	    charge.setEffect_time(EffectDate);
	    charge.setPoints(AllPoint);

	} catch (DocumentException e) {
	    e.printStackTrace();
	}

	return charge;
    }

    /**
     * 订购套餐 http://110.84.128.78:8088/httpIntf/dealIntf ?postData=<Request>
     * <Head><MethodName>IMS_BUY</MethodName> <Spid>802964</Spid>
     * <Appid>279</Appid>
     * <Passwd>e2f76fc3f54568c90543c6882a5fef895da55139</Passwd> </Head>
     * <Body><PointsSpId>100221</PointsSpId><Ims>q</Ims>
     * <Key>w</Key><Type>s</Type><EffectType>s</EffectType></Body> </Request>
     * 
     * @param chargeNbr
     *            IMS账号
     * @param chargeKey
     *            IMS密码
     * @return
     */

    public static String order(String chargeNbr, String chargeKey) {

	StringBuffer urlBuffer = new StringBuffer();
	urlBuffer.append("<Request>");
	urlBuffer.append("<Head><MethodName>IMS_BUY</MethodName>");
	urlBuffer.append("<Spid>" + ProperyResource.getSpId() + "</Spid>");
	urlBuffer.append("<Appid>" + ProperyResource.getAppId() + "</Appid>");
	urlBuffer.append("<Passwd>" + Encrypt.sha1Encrypt(ProperyResource.getPassword()) + "</Passwd>");
	urlBuffer.append("</Head>");
	urlBuffer.append("<Body><PointsSpId>100221</PointsSpId><Ims>" + chargeNbr.trim() + "</Ims>");
	urlBuffer.append("<Key>" + chargeKey.trim() + "</Key><Type>1</Type><EffectType>1</EffectType></Body>");
	urlBuffer.append("</Request>");

	String url = ProperyResource.getServiceUrl() + "?postData=" + URLEncoder.encode(urlBuffer.toString());
	log.info("定购套餐请求---send time account request:" + url);
	// System.out.println("定购套餐请求---send time account request:"+urlBuffer);

	String xml = HttpRequest.getData(url);

	log.info("定购套餐响应---send time account response:" + xml);
	// System.out.println("定购套餐响应---send time account response:"+xml);

	String result = null;
	try {
	    Document doc = DocumentHelper.parseText(xml);
	    Element root = doc.getRootElement();
	    Element head = root.element("Head");
	    Element body = root.element("Body");
	    result = head.elementTextTrim("Result");
	} catch (DocumentException e) {
	    e.printStackTrace();
	}

	if (result != null && !result.equals("0")) {
	    log.info("定购套餐失败");
	}

	return result;
    }

    /**
     * 根据 sessionId 查询话单
     * 
     * @param sessionId
     *            话单唯一标识
     * @return
     */
    public static ResultQueryBillBean billQuery(String sessionId) {

	StringBuffer urlBuffer = new StringBuffer(ProperyResource.getServiceUrl());

	urlBuffer.append("?postData=<Request>");
	urlBuffer.append("<Head><MethodName>IMS_BILL2</MethodName>");
	urlBuffer.append("<Spid>" + ProperyResource.getSpId() + "</Spid>");
	urlBuffer.append("<Appid>" + ProperyResource.getAppId() + "</Appid>");
	urlBuffer.append("<Passwd>" + Encrypt.sha1Encrypt(ProperyResource.getPassword()) + "</Passwd>");
	urlBuffer.append("</Head>");
	urlBuffer.append("<Body>");
	urlBuffer.append("<Sessionid>" + sessionId + "</Sessionid><Type></Type>");
	urlBuffer.append("</Body></Request>");

	String xml = HttpRequest.getDataThreeTime(urlBuffer.toString());
	log.info("session_id=" + sessionId + "----response=" + xml);
	String result = null;

	ResultQueryBillBean querybill = new ResultQueryBillBean();
	List<IMSBilBean> lists = new ArrayList<IMSBilBean>();

	try {

	    Document doc = DocumentHelper.parseText(xml);
	    Element root = doc.getRootElement();
	    Element head = root.element("Head");
	    Element body = root.element("Body");
	    result = head.elementTextTrim("Result");
	    // 判断如果状态为失败，则自动跳出
	    if (result.equals("-1")) {
		querybill.setResult(result);
		querybill.setList(lists);
		return querybill;
	    }

	    List<Element> dataList = body.elements("Data");

	    if (dataList != null && dataList.size() > 0) {

		for (int i = 0; i < dataList.size(); i++) {

		    IMSBilBean bean = new IMSBilBean();
		    Element item = dataList.get(i);
		    String Sessionid = item.element("Sessionid").getTextTrim();
		    String ChargeNbr = item.element("ChargeNbr").getTextTrim();
		    String DisplayNbr = item.element("DisplayNbr").getTextTrim();
		    String CallerNbr = item.element("CallerNbr").getTextTrim();
		    String CalledNbr = item.element("CalledNbr").getTextTrim();
		    String StartTime = item.element("StartTime").getTextTrim();
		    String EndTime = item.element("EndTime").getTextTrim();
		    String BillSubtype = item.element("BillSubtype").getTextTrim();
		    String Duration = item.element("Duration").getTextTrim();

		    bean.setSession_id(Sessionid);
		    bean.setBillSubtype(BillSubtype);
		    bean.setBeginTime(StartTime);
		    bean.setCallee(CalledNbr);
		    bean.setCaller(CallerNbr);
		    bean.setChargeNumber(ChargeNbr);
		    bean.setDisplayNbr(DisplayNbr);
		    bean.setEndTime(EndTime);
		    int time = Integer.parseInt(Duration) % 60 == 0 ? Integer.parseInt(Duration) % 60 : Integer.parseInt(Duration) % 60 + 1;
		    bean.setTime(time);
		    lists.add(bean);

		}

	    }

	} catch (DocumentException e) {
	    e.printStackTrace();
	}

	querybill.setResult(result);
	querybill.setList(lists);

	return querybill;

    }

    /**
     * 发起双方会话(发起一对一通话)
     * 
     * @param callerNbr
     *            发起者
     * @param calleeNbr
     *            被叫者
     * @param poolAbilityInfo
     *            能力配置信息
     * @param displayNbrMode
     *            显号模式
     * @return
     */
    public static DialResultBean dial(String callerNbr, String calleeNbr, PoolAbilityInfoBean poolAbilityInfo, String isRecord, String displayNbrMode) {
	DialResultBean dialResult = new DialResultBean();
	long begin = 0;
	long end = 0;
	double during;
	// 返回值
	String result_desc = "";
	// 返回状态
	String result_status = "";
	// 发起时间
	String displayNbr = "";
	String currentTime = DateUtils.getCurrentTime();

	StringBuffer urlBuffer = new StringBuffer(ProperyResource.getServiceUrl());
	urlBuffer.append("?postData=<Request>");
	urlBuffer.append("<Head><MethodName>Dial</MethodName>");
	urlBuffer.append("<Spid>" + ProperyResource.getSpId() + "</Spid>");
	urlBuffer.append("<Appid>" + ProperyResource.getAppId() + "</Appid>");
	urlBuffer.append("<Passwd>" + Encrypt.sha1Encrypt(ProperyResource.getPassword()) + "</Passwd>");
	urlBuffer.append("</Head>");
	urlBuffer.append("<Body>");

	if (poolAbilityInfo != null) {
	    displayNbr = poolAbilityInfo.getDisplay_number();
	    urlBuffer.append("<DisplayNbr>").append(poolAbilityInfo.getDisplay_number().trim()).append("</DisplayNbr>");
	    urlBuffer.append("<ChargeNbr>").append(poolAbilityInfo.getCharge_number().trim()).append("</ChargeNbr>");
	    urlBuffer.append("<Key>").append(poolAbilityInfo.getCharge_key().trim()).append("</Key>");
	} else {
	    dialResult.setResult("99999");
	    return dialResult;
	}

	urlBuffer.append("<CallerNbr>" + callerNbr + "</CallerNbr>");
	urlBuffer.append("<CalleeNbr>" + calleeNbr + "</CalleeNbr>");
	urlBuffer.append("<AnswerOnMedia>1</AnswerOnMedia>");
	urlBuffer.append("<DisplayNbrMode>" + displayNbrMode + "</DisplayNbrMode>");
	urlBuffer.append("<Record>" + isRecord + "</Record>");
	urlBuffer.append("</Body>");
	urlBuffer.append("</Request>");

	// 调用开始时间点
	begin = Calendar.getInstance().getTimeInMillis();
	String xml = HttpRequest.getDataThreeTime(urlBuffer.toString());
	// 调用结束时间点
	end = Calendar.getInstance().getTimeInMillis();

	String result = null;
	String sessionId = null;
	try {

	    Document doc = DocumentHelper.parseText(xml);
	    Element root = doc.getRootElement();
	    Element head = root.element("Head");
	    Element body = root.element("Body");
	    result = head.elementTextTrim("Result");
	    sessionId = head.elementTextTrim("Sessionid");
	    dialResult.setResult(result);
	    dialResult.setSessionId(sessionId);
	    dialResult.setDisplayNbr(displayNbr);
	    result_desc = xml;
	    result_status = result;

	} catch (DocumentException e) {
	    e.printStackTrace();
	}

	try {
	    during = Double.valueOf((end - begin)) / 1000;
	    logService.logIms(during, AbilityTypeEnum.DIAL_IMS.getKey(), urlBuffer.toString(), result_desc, result_status, currentTime, "IMS", callerNbr);
	} catch (Exception e) {
	    log.info("IMS用户按键回调地址设置接口出现异常！");
	}

	if (result != null && !result.equals("0")) {
	    log.info("发起电话拨号失败");
	}

	return dialResult;
    }

}
